/**
 * Created by LiH on 2018/01/12.
 */
import takeDefaultOptions from '../lib/takeDefaultOptions'
import ConfirmComponent from '../components/ZuicoolConfirm'

let $vm;

const plugin = {
  install(Vue, options){
    const Alert = Vue.extend(ConfirmComponent);

    if(!$vm){
      $vm = new Alert({
        el: document.createElement('div')
      });
      document.body.appendChild($vm.$el)
    }

    const defaults = takeDefaultOptions($vm);

    Vue.$ZCConfirm = {
      show(options = {}){
        if(typeof options === 'string'){
          $vm.text = options
        } else if (typeof options === 'object'){
          options = Object.assign({}, defaults, options);
          for(let i in options){
            if(options.hasOwnProperty(i)){
              $vm[i] = options[i]
            }
          }
        }
        $vm.$off('cancel');
        $vm.$off('confirm');
        $vm.$off('hide');
        $vm.$on('cancel', () => {
          options && options.onCancel && options.onCancel()
        });
        $vm.$on('confirm', () => {
          options && options.onConfirm && options.onConfirm()
        });
        $vm.$on('hide', () => {
          options && options.onHide && options.onHide();
          $vm.visible = false;
        });
        $vm.visible = true;
      },

      hide(){
        $vm.visible = false;
      }
    };

    Vue.mixin({
      created(){
        this.$ZCConfirm = Vue.$ZCConfirm
      }
    })
  }
};

export default plugin
